今天文章的內容是Sum(總和)跟Value Count(數量計算)
今天的示範資料
Sum大家應該都很熟悉了,這邊就不多做解釋,直接進入範例吧
先定個目標,假設我想要統計出資工一2的英文分數總和
query:
"query": {
"term": {
"class": "資工一2"
}
}
aggs query:
"aggs": {
"sum_eng": {
"sum": {
"field": "grades.eng",
"missing": 40
}
}
}
組合起來的query:
{
"query": {
"term": {
"class": "資工一2"
}
},
"aggs": {
"sum_eng": {
"sum": {
"field": "grades.eng",
"missing": 40
}
}
}
}
結果:
"aggregations" : {
"sum_eng" : {
"value" : 212.0
}
}
也可以用腳本調整,假設想幫分數低於60分的人+10分,範例如下
aggs query:
"aggs": {
"sum_eng": {
"sum": {
"field": "grades.eng",
"missing": 40,
"script": {
"lang": "painless",
"source": "if(doc['grades.eng'].value<60){doc['grades.eng'].value+10;}else{doc['grades.eng'].value;}"
}
}
}
}
結果:
"aggregations" : {
"sum_eng" : {
"value" : 222.0
}
}
還有另外一種是針對字段histogram fields的應用,想了解更多的可以去:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html#search-aggregations-metrics-sum-aggregation-histogram-fields
histogram fields說明:
https://www.elastic.co/guide/en/elasticsearch/reference/current/histogram.html
這種聚合方式會回傳指定字段的統計數量
先定個目標,假設我們今天想知道資工一2的班級人數
query
"query": {
"term": {
"class": "資工一2"
}
}
aggs query:
"aggs": {
"class_count": {
"value_count": {
"field": "class"
}
}
}
組合起來的query:
{
"query": {
"term": {
"class": "資工一2"
}
},
"aggs": {
"class_count": {
"value_count": {
"field": "class"
}
}
}
}
結果:
"aggregations" : {
"class_count" : {
"value" : 3
}
}
一樣有針對histogram fields的應用,想了解可以去:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html
今天的文章就到這邊,謝謝大家
請問大大,如果是想要返回每個學生的總分,應該怎麼寫聚合?
total = grades.eng + grades.math + grades.soc+ grades.mand
返回結果類似
{
[name:XXX,total:123],
[name:OOO,total:789]
}
謝謝大大,我來研究一下~